package main.java.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Cilent {
    private Socket socket;

    public Cilent() {
        try {
            socket = new Socket("localhost",8088);
            System.out.println("客户端连接成功");
            Thread t = new Thread() {
                public void run() {
                    receiveMsg();
                }
            };
            t.start();
        } catch (IOException e) {
            System.out.println("客户端连接失败");
            e.printStackTrace();
        }
    }
    public void start() {
        Scanner sc = new Scanner(System.in);
        try {
            OutputStream outputStream = socket.getOutputStream();
            while (true) {
                String msg = sc.nextLine();
                if ("exit".equals(msg)){
                    break;
                }
                byte[] data = msg.getBytes();
                outputStream.write(data.length);
                outputStream.write(data);
            }
        } catch (IOException e) {
            System.out.println("客户端发送消息失败");
            e.printStackTrace();
        }finally {
            try {
                socket.close();
                System.out.println("客户端已退出");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void receiveMsg() {
        try {
            InputStream inputStream = socket.getInputStream();
            int len;
            byte[] data = new byte[1024];
            while ((len = inputStream.read(data)) != -1){
                String message = new String(data, 0,len,StandardCharsets.UTF_8);
                System.out.println("收到群发：" + message);
            }
        } catch (IOException e) {
            if(socket.isClosed()){
                System.out.println("客户端关闭，停止接收消息");
            }else {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Cilent cilent = new Cilent();
        cilent.start();
    }
}
